package com.masterclient.app.modules.shop;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.base.FragmentHostActivity;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseFragment;
import com.masterclient.app.R;
import com.masterclient.app.modules.order.OrderDetailActivity;
import com.masterclient.app.modules.shop.adapter.StockChangeAdapter;
import com.masterclient.app.modules.shop.beans.StockChangeBean;
import com.masterclient.app.modules.shop.contract.StockChangeContract;
import com.masterclient.app.modules.shop.contract.StockChangePresenter;
import com.masterclient.app.modules.shop.widget.StockFilterPopupWindow;
import com.eoner.uikit.header.MyRefreshHead;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @auther hxm
 * @date 2020/4/8.
 */
@Route(path = AroutePath.STOCK_CHANGE_FRAGMENT)
public class StockChangeFragment extends BaseFragment<StockChangePresenter> implements StockChangeContract.View {

    public static final String PRODUCT_ID = "productId";

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.view_head)
    View viewHead;
    @BindView(R.id.view_other)
    View viewOther;
    @BindView(R.id.tv_sku)
    TextView tvSku;
    @BindView(R.id.iv_sku)
    ImageView ivSku;
    @BindView(R.id.tv_stock)
    TextView tvStock;
    @BindView(R.id.iv_stock)
    ImageView ivStock;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.iv_type)
    ImageView ivType;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.view_sku)
    View viewSku;
    @BindView(R.id.view_stock_change)
    View viewStock;
    @BindView(R.id.view_type)
    View viewType;
    @BindView(R.id.view_time)
    View viewTime;
    private View footView;
    @BindView(R.id.view_empty)
    View emptyView;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;
    @BindView(R.id.tv_stock_num)
    TextView tvStockNum;
    @BindView(R.id.tv_stock_des)
    TextView tvStockDes;

    private StockFilterPopupWindow popupWindow;
    private StockChangeAdapter stockChangeAdapter;
    private int page = 1;
    private boolean hasMore;
    private StockChangeBean dataBean;
    private List<StockChangeBean.ChangeBean> list;
    private String productId;
    private String spec = "-1";
    private String changeType = "-1";
    private String stockType = "-1";
    private String timeType = "-1";
    private String timeStart = "";
    private String timeEnd = "";
    private boolean isSelected =  false;
    private String specValue = "0";
    private String changeValue = "0";
    private String stockValue = "0";
    private String timeValue = "0";

    public static StockChangeFragment getInstance(String productId) {
        StockChangeFragment fragment = new StockChangeFragment();
        Bundle bundle = new Bundle();
        bundle.putString(PRODUCT_ID, productId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View getRootView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_stock_change, null);
    }

    @Override
    protected void initOnlyOnce() {
        super.initOnlyOnce();

        productId = getArguments().getString(PRODUCT_ID);
        refreshLayout.setRefreshHeader(new MyRefreshHead(getActivity()));
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            page = 1;
            mPresenter.getStockChange(productId, spec, changeType, stockType, timeType, timeStart, timeEnd, String.valueOf(page));
        });

        stockChangeAdapter = new StockChangeAdapter(getActivity());
        stockChangeAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (dataBean == null || dataBean.changeList == null||
                    dataBean.changeList.get(position).redirectParams == null){
                return;
            }
            String redirectType = dataBean.changeList.get(position).redirectType;
            String orderNo = dataBean.changeList.get(position).redirectParams.orderNo;
            String orderId = dataBean.changeList.get(position).redirectParams.orderId;
            String orderProductId = dataBean.changeList.get(position).redirectParams.orderProductId;
            String refundNo = dataBean.changeList.get(position).redirectParams.refundNo;
            if ("2".equals(redirectType)){
                //采购订单详情
                Intent intent = new Intent(mContext, OrderDetailActivity.class);
                intent.putExtra("order_no", orderNo);
                intent.putExtra("from_type", "purchase");
                mContext.startActivity(intent);
            } else if ("3".equals(redirectType)) {
                //销售订单详情
                ARouter.getInstance().build(AroutePath.SALE_ORDER_DETAIL_ACTIVITY)
                        .withString("order_no", orderNo)
                        .navigation();
            } else if ("4".equals(redirectType)){
                //售后详情 买家
                ARouter.getInstance().build(AroutePath.AFTER_SALE_PURCHASE_DETAIL_ACTIVITY)
                        .withString("order_product_id", orderProductId)
                        .withString("order_id", orderId).navigation();
            } else if ("5".equals(redirectType)){
                //售后详情 卖家
                Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.REFUND_DETAILS_FRAGMENT)
                        .withString("refundNo",refundNo)
                        .withString("order_product_id",orderProductId)
                        .withString("order_id",orderId)
                        .navigation();
                FragmentHostActivity.openFragment(mContext, fragment);
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setAdapter(stockChangeAdapter);
        stockChangeAdapter.bindToRecyclerView(recyclerView);

        footView = View.inflate(mContext, R.layout.view_foot_text, null);
        footView.setVisibility(View.GONE);
        View viewFooter = footView.findViewById(R.id.view_footer);
        viewFooter.setBackgroundColor(Color.parseColor("#00000000"));
        stockChangeAdapter.setFooterView(footView);
        stockChangeAdapter.setOnLoadMoreListener(() -> {
            if (hasMore) {
                page++;
                mPresenter.getStockChange(productId, spec, changeType, stockType, timeType, timeStart, timeEnd, String.valueOf(page));
            }
        }, recyclerView);
        mPresenter.getStockChange(productId, spec, changeType, stockType, timeType, timeStart, timeEnd, String.valueOf(page));
    }

    @OnClick({R.id.view_sku, R.id.view_stock_change, R.id.view_type, R.id.view_time})
    void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.view_sku:
                viewSku.setBackgroundResource(R.drawable.bg_stock_change_selected);
                ivSku.setImageResource(R.mipmap.icon_stock_change_up);
                tvSku.setTextColor(Color.parseColor("#FF6809"));
                displayPopupWindow(viewHead, 1, new StockFilterPopupWindow.CallBack() {
                    @Override
                    public void dismiss() {
                        dismissPopupWindow();
                        viewSku.setBackgroundResource(R.drawable.shape_radius14_f0f2f5);
                        ivSku.setImageResource(R.mipmap.icon_stock_change_down);
                        tvSku.setTextColor(Color.parseColor("#141922"));
                    }

                    @Override
                    public void OnSelect(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean) {
                        specValue = tabBean.value;
                        tvSku.setText(tabBean.title);
                        popupWindow.dismiss();
                        dismissPopupWindow();
                        viewSku.setBackgroundResource(R.drawable.shape_radius14_f0f2f5);
                        ivSku.setImageResource(R.mipmap.icon_stock_change_down);
                        tvSku.setTextColor(Color.parseColor("#141922"));
                        spec = tabBean.value;
                        page = 1;
                        isSelected = true;
                        mPresenter.getStockChange(productId, spec, changeType, stockType, timeType, timeStart, timeEnd, String.valueOf(page));
                    }

                    @Override
                    public void OnSelectTime(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean, String startTime, String endTime, String time) {

                    }
                });
                break;
            case R.id.view_stock_change:
                viewStock.setBackgroundResource(R.drawable.bg_stock_change_selected);
                ivStock.setImageResource(R.mipmap.icon_stock_change_up);
                tvStock.setTextColor(Color.parseColor("#FF6809"));
                displayPopupWindow(viewHead, 2, new StockFilterPopupWindow.CallBack() {
                    @Override
                    public void dismiss() {
                        dismissPopupWindow();
                        viewStock.setBackgroundResource(R.drawable.shape_radius14_f0f2f5);
                        ivStock.setImageResource(R.mipmap.icon_stock_change_down);
                        tvStock.setTextColor(Color.parseColor("#141922"));
                    }

                    @Override
                    public void OnSelect(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean) {
                        changeValue = tabBean.value;
                        tvStock.setText(tabBean.title);
                        popupWindow.dismiss();
                        dismissPopupWindow();
                        viewStock.setBackgroundResource(R.drawable.shape_radius14_f0f2f5);
                        ivStock.setImageResource(R.mipmap.icon_stock_change_down);
                        tvStock.setTextColor(Color.parseColor("#141922"));
                        changeType = tabBean.value;
                        page = 1;
                        isSelected = true;
                        mPresenter.getStockChange(productId, spec, changeType, stockType, timeType, timeStart, timeEnd, String.valueOf(page));
                    }

                    @Override
                    public void OnSelectTime(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean, String startTime, String endTime, String time) {

                    }
                });
                break;
            case R.id.view_type:
                viewType.setBackgroundResource(R.drawable.bg_stock_change_selected);
                ivType.setImageResource(R.mipmap.icon_stock_change_up);
                tvType.setTextColor(Color.parseColor("#FF6809"));
                displayPopupWindow(viewHead, 3, new StockFilterPopupWindow.CallBack() {
                    @Override
                    public void dismiss() {
                        dismissPopupWindow();
                        viewType.setBackgroundResource(R.drawable.shape_radius14_f0f2f5);
                        ivType.setImageResource(R.mipmap.icon_stock_change_down);
                        tvType.setTextColor(Color.parseColor("#141922"));
                    }

                    @Override
                    public void OnSelect(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean) {
                        stockValue = tabBean.value;
                        tvType.setText(tabBean.title);
                        popupWindow.dismiss();
                        dismissPopupWindow();
                        viewType.setBackgroundResource(R.drawable.shape_radius14_f0f2f5);
                        ivType.setImageResource(R.mipmap.icon_stock_change_down);
                        tvType.setTextColor(Color.parseColor("#141922"));
                        stockType = tabBean.value;
                        page = 1;
                        isSelected = true;
                        mPresenter.getStockChange(productId, spec, changeType, stockType, timeType, timeStart, timeEnd, String.valueOf(page));
                    }

                    @Override
                    public void OnSelectTime(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean, String startTime, String endTime, String time) {

                    }
                });
                break;
            case R.id.view_time:
                tvTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.icon_stock_change_time_up, 0);
                displayPopupWindow(viewOther, 4, new StockFilterPopupWindow.CallBack() {
                    @Override
                    public void dismiss() {
                        dismissPopupWindow();
                        tvTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.icon_stock_change_time_down, 0);
                    }

                    @Override
                    public void OnSelect(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean) {

                    }

                    @Override
                    public void OnSelectTime(StockChangeBean.SearchSelectBean.specBean.defaultBean tabBean, String startTime, String endTime, String time) {
                        if (tabBean != null) {
                            timeValue = tabBean.value;
                            tvTime.setText(tabBean.title);
                            timeType = tabBean.value;
                            timeStart = "";
                            timeEnd = "";
                        } else {
                            tvTime.setText(time);
                            timeType = "99";
                            timeStart = startTime;
                            timeEnd = endTime;
                        }
                        tvTime.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.icon_stock_change_time_down, 0);
                        popupWindow.dismiss();
                        dismissPopupWindow();
                        page = 1;
                        isSelected = true;
                        mPresenter.getStockChange(productId, spec, changeType, stockType, timeType, timeStart, timeEnd, String.valueOf(page));
                    }
                });
                break;
        }
    }

    private void displayPopupWindow(View view, int type, StockFilterPopupWindow.CallBack callBack) {
        if (dataBean == null) {
            return;
        }
        if (popupWindow == null) {
            if (type == 1) {
                popupWindow = new StockFilterPopupWindow(getActivity(), dataBean.searchSelect.spec.list, type,specValue, callBack);
            } else if (type == 2) {
                popupWindow = new StockFilterPopupWindow(getActivity(), dataBean.searchSelect.changeType.list, type,changeValue, callBack);
            } else if (type == 3) {
                popupWindow = new StockFilterPopupWindow(getActivity(), dataBean.searchSelect.stockType.list, type,stockValue, callBack);
            } else if (type == 4) {
                popupWindow = new StockFilterPopupWindow(getActivity(), dataBean.searchSelect.timeType.list, type,timeValue, callBack);
            }
        }
        popupWindow.showAsDropDown(view);
        popupWindow.setOutsideTouchable(true);
    }

    private void dismissPopupWindow() {
        if (popupWindow != null) {
            popupWindow = null;
        }
    }

    @Override
    public void showData(StockChangeBean dataBean) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
        if (dataBean != null) {
            this.dataBean = dataBean;

            //上半部分信息
            tvStockNum.setText(dataBean.totalStock);
            tvStockDes.setText(String.format("家里库存收支 %s  仓库库存收支 %s", dataBean.homeStock, dataBean.storeStock));
            if (dataBean.searchSelect != null && !isSelected) {
                if (dataBean.searchSelect.spec != null && dataBean.searchSelect.spec.defaultBean != null) {
                    tvSku.setText(dataBean.searchSelect.spec.defaultBean.title);
                    specValue = dataBean.searchSelect.spec.defaultBean.value;
                }
                if (dataBean.searchSelect.changeType != null && dataBean.searchSelect.changeType.defaultBean != null) {
                    tvStock.setText(dataBean.searchSelect.changeType.defaultBean.title);
                    changeValue = dataBean.searchSelect.changeType.defaultBean.value;
                }
                if (dataBean.searchSelect.stockType != null && dataBean.searchSelect.stockType.defaultBean != null) {
                    tvType.setText(dataBean.searchSelect.stockType.defaultBean.title);
                    stockValue = dataBean.searchSelect.stockType.defaultBean.value;
                }
                if (dataBean.searchSelect.timeType != null && dataBean.searchSelect.timeType.defaultBean != null) {
                    tvTime.setText(dataBean.searchSelect.timeType.defaultBean.title);
                    timeValue = dataBean.searchSelect.timeType.defaultBean.value;
                }
            }
            //下半部分列表信息
            setEmptyStatus(3);
            hasMore = dataBean.hasMore;
            if (list == null) {
                list = new ArrayList<>();
            }
            if (page == 1) {
                list.clear();
            }
            list.addAll(dataBean.changeList);
            stockChangeAdapter.setNewData(list);

            if (list.size() <= 0) {
                setEmptyStatus(1);
            } else {
                if (!hasMore) {
                    stockChangeAdapter.setEnableLoadMore(false);
                    stockChangeAdapter.loadMoreEnd();
                    footView.setVisibility(View.VISIBLE);
                } else {
                    stockChangeAdapter.loadMoreComplete();
                    footView.setVisibility(View.GONE);
                }
            }
            stockChangeAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 设置页面置空状态
     *
     * @param status status == 1：数据返回为空
     */
    private void setEmptyStatus(int status) {
        if (status == 1) {
            emptyView.setVisibility(View.VISIBLE);
            tvTip.setText("还没有库存变更记录哦～");
            tvTip.setTextColor(Color.parseColor("#F23051"));
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tvTip.getLayoutParams();
            params.topMargin = ScreenUtils.dp2px(24);
            tvTip.setLayoutParams(params);
            ivEmpty.setImageResource(R.mipmap.icon_null);
            footView.setVisibility(View.GONE);
        } else {
            emptyView.setVisibility(View.GONE);
        }
    }

    @Override
    public void showDataFailed(String msg) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh(false);
        }
        ToastUtil.showToast(msg);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
